#ifndef __adc_H
#define __adc_H
#ifdef __cplusplus
 extern "C" {
#endif

/* Includes ------------------------------------------------------------------*/
#include "bsp/bsp.h"
#include "os/types.h"

void adc_init(void);
void adc_start_convert(void);
void adc_stop_convert(void);
void adc_get_phase_curr_value(u8 chan, s16 *adc1, s16 *adc2);
u16 adc_get_dc_voltage_value(void);
u16 adc_get_mot_temp_value(void);
u16 adc_get_aux_temp_value(void);
u16 adc_get_throttle_value(void);
u16 adc_get_mos_temp_value(void);
void adc_get_phase_voltage_value(u16 *uvw);
u16 adc_get_vrefint_value(void);

//#define CONFIG_ADC2_3_IU_IV

#ifdef STM32F405xx
extern ADC_HandleTypeDef hadc2;
extern ADC_HandleTypeDef hadc3;

#define __HAL_ADC_StartConversionExtTrig(__HANDLE__, ext_tri_edge) SET_BIT((__HANDLE__)->Instance->CR2, ext_tri_edge)
#define __HAL_ADC_StopConversionExtTrig(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CR2, ADC_CR2_JEXTEN)
/* Enable ADC DMA mode */
#define __HAL_ADC_ENABLE_DMA(__HANDLE__)   (__HANDLE__)->Instance->CR2 |= ADC_CR2_DMA
#define __HAL_ADC_START_SW(__HANDLE__)  (__HANDLE__)->Instance->CR2 |= (uint32_t)ADC_CR2_SWSTART;

static __INLINE void adc_wait_clear_inj_chans(void) {

	while(!__HAL_ADC_GET_FLAG(&hadc2, ADC_FLAG_JEOC)
#ifdef CONFIG_ADC2_3_IU_IV
		|| !__HAL_ADC_GET_FLAG(&hadc3, ADC_FLAG_JEOC) // wait 2 adcs
#endif
	);
	__HAL_ADC_CLEAR_FLAG(&hadc2, ADC_FLAG_JEOC);
#ifdef CONFIG_ADC2_3_IU_IV
	__HAL_ADC_CLEAR_FLAG(&hadc3, ADC_FLAG_JEOC);
#endif
}

static __INLINE void adc_enable_ext_trigger(void) {
	__HAL_ADC_StartConversionExtTrig(&hadc2, ADC_EXTERNALTRIGINJECCONVEDGE_RISING);
#ifdef CONFIG_ADC2_3_IU_IV
	__HAL_ADC_StartConversionExtTrig(&hadc3, ADC_EXTERNALTRIGINJECCONVEDGE_RISING);
#endif
}

static __INLINE void adc_disable_ext_trigger(void) {
	__HAL_ADC_StopConversionExtTrig(&hadc2);
#ifdef CONFIG_ADC2_3_IU_IV
	__HAL_ADC_StopConversionExtTrig(&hadc3);
#endif
}
#else
extern ADC_HandleTypeDef hadc1;
extern ADC_HandleTypeDef hadc2;

static __INLINE void adc_wait_clear_inj_chans(void) {
	if(__HAL_ADC_GET_FLAG(&hadc1, ADC_FLAG_JEOC)) {
		__HAL_ADC_CLEAR_FLAG(&hadc1, ADC_FLAG_JEOC);
		__HAL_ADC_CLEAR_FLAG(&hadc2, ADC_FLAG_JEOC);
	}
}

static __INLINE void adc_enable_ext_trigger(void) {
	LL_ADC_INJ_StartConversion(hadc1.Instance);
}

static __INLINE void adc_disable_ext_trigger(void) {
	LL_ADC_INJ_StopConversion(hadc1.Instance);
}

#endif
/* just for build success */
static __INLINE void adc_normal_sample(void) {

}


#ifdef __cplusplus
}
#endif
#endif /*__ adc_H */

/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
